package com.luozhili.rabbitmqlearningdemo.work_demo;

import com.rabbitmq.client.*;

import java.io.IOException;

public class Recv {
    private final static String QUEUE_NAME = "learn_queue_1";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.31.226");
        factory.setUsername("zhangsan");
        factory.setPassword("123456");
        factory.setVirtualHost("/shopping");

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //* 一次性只能抓取一个任务。  加上这个就能实行能者多劳
        channel.basicQos(1);

        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");


        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                String message = new String(body);
                System.out.println(" [x] Received '" + message + "'");

                //* 模拟程序执行速度
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


                channel.basicAck(envelope.getDeliveryTag(),false);


            }
        };
        //等待新消息，不关闭  ， false 设置手动 ACK
        channel.basicConsume(QUEUE_NAME, false, consumer);

    }
}
